import React, { PropsWithChildren, useRef, useState } from "react";
import { useDroppable, useDndMonitor, Active } from "@dnd-kit/core";
import classNames from "classnames";
import { useHover } from "ahooks";
import { FunFormElement } from "../../core";
import styles from "../index.module.less";

const DropItem = (
  props: PropsWithChildren<{
    id: string;
    validAf?: boolean;
    onDrop(active: Active): void;
  }>
) => {
  const { id, validAf, onDrop } = props;
  const { setNodeRef, isOver } = useDroppable({
    id,
  });
  const [isAwaysFull, setIsAwaysFull] = useState(false);

  useDndMonitor({
    onDragEnd({ active, over }) {
      setIsAwaysFull(false);
      if (over?.id !== props.id) return;
      onDrop(active);
    },
    onDragOver({ active, over }) {
      if (over?.id !== props.id || !active) {
        setIsAwaysFull(false);
        return;
      }
      let { name, value } = active.data.current as {
        name: FunFormElement;
        value: WidgetCategory | FunFormWidget;
      };
      if (name === FunFormElement.Cagetroy) {
        const { allwaysFull } = value as WidgetCategory;
        setIsAwaysFull(!!allwaysFull);
      } else if (name === FunFormElement.Widget) {
        const { allwaysFull: alf } = (value as FunFormWidget).category;
        setIsAwaysFull(!!alf);
      }
    },
    onDragCancel() {
      setIsAwaysFull(false);
    },
  });
  const ref = useRef(null);

  const isHovering = useHover(ref);
  return (
    <div className={styles.droped} ref={setNodeRef}>
      <div
        ref={ref}
        className={classNames(
          styles.blockDrop,
          isHovering && styles.isHovering,
          isOver && styles.isCover
        )}
      >
        {validAf && (
          <div
            className={styles.tip}
            style={{
              fontSize: isAwaysFull ? 12 : 14,
              color: isAwaysFull ? "red" : "#727272",
            }}
          >
            {isAwaysFull
              ? "整行占位组件无法放置在此处"
              : "点击或者拖入左侧组件"}
          </div>
        )}
      </div>
    </div>
  );
};

export default DropItem;
